package com.example.xungeng2.controller;

import com.example.xungeng2.common.Result;
import com.example.xungeng2.mapper.RiskInfoMapper;
import com.example.xungeng2.mapper.WorkerMapper;
import com.example.xungeng2.pojo.SendInfo;
import com.example.xungeng2.pojo.User;
import com.example.xungeng2.pojo.Xglx;
import com.example.xungeng2.service.UserService;
import com.example.xungeng2.service.WorkerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@Slf4j
@RequestMapping("/api/worker")
public class WorkerController {

    @Value("${patrol.path}")
    private String uploadPath;

    @Autowired
    private UserService userService;

    @Autowired
    private WorkerService workerService;

    @Autowired
    private RiskInfoMapper riskInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WorkerMapper workerMapper;


    /**
     * 添加了微信小程序的发送riskinfo风险信息的功能
     * @param userId
     * @param message
     * @return
     */
    @GetMapping("/sendRiskInfo")
    public Result uploadLocation(@RequestParam(value = "userId") Integer userId,
                                 @RequestParam(value = "message") String message) {
        Result result = new Result();
//        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String s = date.toString();
        User user = userService.getById(userId);
        String realName = user.getRealName();
        Integer insert = riskInfoMapper.insertRiskInfo(userId, realName, message, s,1);
        if (insert==1) {
            result.setCode(200);
        }else {
            result.setCode(202);
        }
        return result;
    }

    @GetMapping("/XGSelectInfo/{userId}")
    public Result XGSelectInfo(@PathVariable Integer userId) {
        List<SendInfo> list = workerService.selectInfo(userId);
        for (int i=0;i<list.size();i++){
            String s = userService.selectUserRealNameById(list.get(i).getAdminId());
            Map<String,Object> param = new HashMap<>();
            param.put("adminrealName",s);
            list.get(i).setParam(param);

            String imgUrl = list.get(i).getImgUrl();
            String replace1 = imgUrl.replace("[", "");
            String replace2 = replace1.replace("]", "");
            list.get(i).setImgUrl(replace2);
        }
        return Result.ok(list);
    }

    @GetMapping("/findUserClock/{userId}")
    public Result findUserClock(@PathVariable Integer userId) {
        Result result = new Result();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String time = df.format(new Date());
        Integer userClock = workerService.findUserClock(userId, time);
        if (userClock==null){
            result.setCode(0);
        }else {
            result.setCode(1);
        }
        List<String> historyUserClock = workerService.findHistoryUserClock(userId);
        result.setData(historyUserClock);
        return result;
    }

    @GetMapping("/userClock/{userId}")
    public Result userClock(@PathVariable Integer userId) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String time = df.format(new Date());
        workerService.userClock(userId,time);

        String realName = userService.selectUserRealNameById(userId);
        DateFormat dfDetail = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String detailTime = dfDetail.format(new Date());
        workerService.addUserKQTJ(userId, realName, time, detailTime);
        return Result.ok();
    }


    /**
     * 更新巡更人员位置
     * @param userId
     * @param latitudeX
     * @param longitudeY
     * @return
     */
    @GetMapping("/uploadLocation")
    public Result uploadLocation(@RequestParam(value = "userId") Integer userId,
                                 @RequestParam(value = "latitudeX") Double latitudeX,
                                 @RequestParam(value = "longitudeY") Double longitudeY){
        User byId = userService.getById(userId);
        if (byId.getIsAssigned()==1){
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String locationRedisKey = "location:" + userId + ":" + df.format(new Date());
            redisTemplate.opsForHash().put(locationRedisKey,"latitudeX",latitudeX);
            redisTemplate.opsForHash().put(locationRedisKey, "longitudeY", longitudeY);

            //保存用户巡更轨迹
            String userLocusRedisKey = "userlocus:" + userId;
            redisTemplate.opsForList().leftPush(userLocusRedisKey, locationRedisKey);

            //更新巡更人员现在的位置
            String userNowAtRedisKey = "userNowAt:" + userId;
            redisTemplate.opsForHash().put(userNowAtRedisKey,"latitudeX",latitudeX);
            redisTemplate.opsForHash().put(userNowAtRedisKey, "longitudeY", longitudeY);
            return Result.ok(200);
        }
        return Result.fail();
    }

    /**
     * 用户结束第一次巡更阶段  workerMapper
     * @param userId
     * @return
     */
    @GetMapping("/onceOverXGLX//{userId}")
    public Result onceOverXGLX(@PathVariable Integer userId) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String overTime = df.format(new Date());
        Integer id = workerMapper.selectXGLXId(userId);
        workerMapper.insertXGLXOverTime(overTime, id);

        String startTime = workerMapper.selectStartTime(userId);
        String userLocusRedisKey = "userlocus:" + userId;
        List list = redisTemplate.opsForList().range(userLocusRedisKey,0,-1);

        String userXGLXRedisKey = "userlocus:" + userId + ":" + startTime + ":" + overTime;
        for (int i=0;i<list.size();i++){
            redisTemplate.opsForList().leftPush(userXGLXRedisKey, list.get(i));
        }
        redisTemplate.delete(userLocusRedisKey);

        workerService.updateXGLXSign(userId);
        String s1 = "userNowAt:" + userId;
        redisTemplate.delete(s1);

        int num = workerService.selectRWLCNumById(userId);

        DateFormat df11 = new SimpleDateFormat("yyyy-MM-dd");
        Integer kqTableId = workerService.selectUserToday(userId,df11.format(new Date()));
        if(null != kqTableId){
            workerService.updateUserKQTJ(userId,num);
        }
        return Result.ok();
    }

    @GetMapping("/onceStartXGLX//{userId}")
    public Result onceStartXGLX(@PathVariable Integer userId) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = df.format(new Date());
        workerMapper.insertXGLX(userId, startTime);
        return Result.ok();
    }

    @GetMapping("/selectXGHistory/{userId}")
    public Result selectXGHistory(@PathVariable Integer userId){
        List<Xglx> xglxes = workerMapper.selectXGHistory(userId);
        Map<Integer, List> mmm = new HashMap<>();
        List<List> list2 = new ArrayList<>();

        for (int i=0;i<xglxes.size();i++){
            String s1 = "userlocus:" + userId + ":" + xglxes.get(i).getStartTime() + ":" + xglxes.get(i).getOverTime();
            List<String> list = redisTemplate.opsForList().range(s1,0,-1);
            List<Map<String, Object>> list1 = new ArrayList<>();

            Map<String, Object> timeMap = new HashMap<>();
            timeMap.put("startTime", xglxes.get(i).getStartTime());
            timeMap.put("overTime", xglxes.get(i).getOverTime());
            list1.add(timeMap);
            System.out.println(list);
            for (int j=0;j<list.size();j++){
                System.out.println(list.get(j));
                Object latitudeX = redisTemplate.opsForHash().get(list.get(j), "latitudeX");
                Object longitudeY = redisTemplate.opsForHash().get(list.get(j), "longitudeY");
                String o = (String) list.get(j);
                String time = o.replace("location:" + userId + ":", "");
                Map<String, Object> m1 = new HashMap<>();
                m1.put("latitudeX", latitudeX);
                m1.put("longitudeY", longitudeY);
                m1.put("time", time);
                list1.add(m1);
            }
            list2.add(list1);
        }

        System.out.println(list2);
        return Result.ok(list2);
    }

    @GetMapping("/selectOneXGHistory")
    public Result selectXGHistory(@RequestParam(value = "userId") Integer userId,
                                  @RequestParam(value = "startTime") String startTime,
                                  @RequestParam(value = "overTime") String overTime){
        System.out.println(userId);
        System.out.println(startTime);
        System.out.println(overTime);
        String s1 = "userlocus:" + userId + ":" + startTime + ":" + overTime;
        List<String> list = redisTemplate.opsForList().range(s1,0,-1);
        list.add("nihai");
        list.add("haode");
        List<Map<String, Object>> list1 = new ArrayList<>();

        for (int j=0;j<list.size();j++){
            System.out.println(list.get(j));
            Object latitudeX = redisTemplate.opsForHash().get(list.get(j), "latitudeX");
            Object longitudeY = redisTemplate.opsForHash().get(list.get(j), "longitudeY");
            String o = (String) list.get(j);
            String time = o.replace("location:" + userId + ":", "");
            Map<String, Object> m1 = new HashMap<>();
            m1.put("latitudeX", latitudeX);
            m1.put("longitudeY", longitudeY);
            m1.put("time", time);
            list1.add(m1);
        }
        return Result.ok(list1);
    }

    @RequestMapping(path = "/Info/{fileName}", method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        // 服务器存放路径
        fileName = uploadPath + "/" + fileName;
        // 文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // 响应图片
        response.setContentType("image/" + suffix);
        try (
                FileInputStream fis = new FileInputStream(fileName);
                OutputStream os = response.getOutputStream();
        ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("失败！！");
        }
    }


}
